//
//  UserAccount.swift
//  MySinaWeiBo
//
//  Created by zhangfuwei on 15/7/31.
//  Copyright © 2015年 zhangfuwei. All rights reserved.
//
//{
//    "access_token" = "2.00PzcfOC0wUdiR3731ee233173nJRC";
//    "expires_in" = 157679999;
//    "remind_in" = 157679999;
//    uid = 2049055685;
//}

import UIKit

class UserAccount: NSObject ,NSCoding{
    
    // MARK: 判断用户的登录与否
   class func userLogin() ->Bool {

        return UserAccount.loadUserAcount() != nil ? true : false
    }
    
    
    
    ///  设置用户相关的信息账户模型的属性
    var access_token : String?
    ///  token 有效时间
    var expires_in : NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
    var uid : String?
    /// 用户名称
    var name: String?
    /// 用户头像地址（大图），180×180
    var avatar_large: String?
    
    
    
    //  基本数据类型的属性在init 初始化时不会分配空间
    //  Property 'self.uid' not initialized at super.init call
    init(dict:[ String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        UserAccount.userAccount = self
    }
    
    // MARK: 加载用户信息
    func loadUserInf(finished:(error:NSError?) ->()) {
        
        NetworkTools.sharedTools.loadUserInf(uid!) { (result, error) -> () in
            //  如果错误不为空,就抛出错误
            if error != nil || result == nil {
                
                print(error )
                finished(error: error )
                return
            }
            //  如果错误为空,且有数据
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //  保存用户信息
            
            self.saveUserAccount()
         print("模型里打印用户信息")
//            print(result)
            finished(error: nil )
        }
    }
    
    
    //  获取存储用户信息路径
    static private let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    // MARK: 保存,获取帐号
     func saveUserAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.path)
    }
    
    /// 加载用户帐号(将保存到磁盘中的用户帐号取出来并存入缓存中,以便后续网络访问使用)
    static  var userAccount : UserAccount?
     class func loadUserAcount() ->UserAccount?{
        if userAccount == nil {
            //  如果是第一次登录,没有保存过,则从磁盘取出的帐号仍可能是 nil
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.path) as? UserAccount
        }
         if let  date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            ///  测试代码
            userAccount = nil
        }
        
        return userAccount
    }
    
    //  归档解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token , forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.uid = aDecoder.decodeObjectForKey("uid") as? String
        self.name = aDecoder.decodeObjectForKey("name") as? String
        self.avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        self.expires_in = aDecoder.decodeDoubleForKey("expires_in")
        self.expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
    
    
    //  防止没有字典中的键,从而报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }

    //  重写 description 方法
    override var description: String  {
        
        let properties = ["access_token","expires_in","expiresDate","name","uid","avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
}
